package com.qingxin.park.action;

import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qingxin.park.entity.BatchProducts;
import com.qingxin.park.entity.BatchProductsReport;
import com.qingxin.park.entity.BatchProductsView;
import com.qingxin.park.entity.Company;
import com.qingxin.park.entity.Crops;
import com.qingxin.park.entity.FarmPark;
import com.qingxin.park.entity.ParkBlock;
import com.qingxin.park.entity.ParkBlockPlantView;
import com.qingxin.park.service.BatchProductsReportService;
import com.qingxin.park.service.BatchProductsService;
import com.qingxin.park.service.CompanyService;
import com.qingxin.park.service.CropsService;
import com.qingxin.park.service.FarmParkService;
import com.qingxin.park.service.ParkBlockPlantService;
import com.qingxin.park.service.ParkBlockService;
import com.qingxin.qrCode.service.QrNumService;
import com.qingxin.sys.action.BaseAction;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.entity.MyUploadFile;
import com.qingxin.sys.entity.MyUploadFileParam;
import com.qingxin.sys.entity.MyUploadFiles;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.support.JsTreeNode;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.support.UploadFile;
import com.qingxin.sys.utils.ExcelUtil;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.ui.bean.TreeNode;

/**
 * 批次产品，追溯物
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/products")
public class BatchProductsAction extends BaseAction {
	
	@Autowired
	private ParkBlockPlantService parkBlockPlantService;
	@Autowired
	private BatchProductsService batchProductsService;
	@Autowired
	private CropsService cropsService;
	
	@Autowired
	private CompanyService companyService;
	@Autowired
	private FarmParkService farmParkService;
	@Autowired
	private ParkBlockService parkBlockService;
	
	@Autowired
	private QrNumService qrNumService;
	
	
	@Autowired
	private BatchProductsReportService batchProductsReportService;
	
	@RequestMapping(value="/qiyejstree.json", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object cropsjgjstree(String pdatatype,String pdttype, String pid, HttpServletRequest request){
		LoginUser loginUser = getLoginUser(request);
		if(StringUtils.isEmpty(pid) || "#".equals(pid)){
			List<TreeNode> clist = companyService.getCompanyData(loginUser);
			List<JsTreeNode> list = new ArrayList<>();
			for(TreeNode treeNode : clist){
				list.add(new JsTreeNode(treeNode.getId(), treeNode.getName(), "COMP", null, true));
			}
			return list;
		}else if("COMP".equals(pdatatype)){
			//String companyid = null;
			List<TreeNode> clist = farmParkService.getUITreeDataCompany(pid, pdttype, loginUser, false);
			List<JsTreeNode> list = new ArrayList<>();
			for(TreeNode treeNode : clist){
				list.add(new JsTreeNode(treeNode.getId(), treeNode.getName(), "PARK", null, true));
			}
			return list;
		}else if("PARK".equals(pdatatype)){
			List<TreeNode> clist = parkBlockService.getUITreeDataType(pid, pdttype,false, loginUser);
			List<JsTreeNode> list = new ArrayList<>();
			for(TreeNode treeNode : clist){
				list.add(new JsTreeNode(treeNode.getId(), treeNode.getName(), "BLOCK", null, false));
			}
			return list;
		}
		return new ArrayList<Object>();
	}
	
	/**
	 * 产品列表
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/list.do", method=RequestMethod.GET)
	public String list(ModelMap model,String pdttype, HttpServletRequest request){
		model.put("pdttype", pdttype);
		return "/trace/products/products_list";
	}
	
	/**
	 * 列表分页数据
	 * @param leftdata
	 * @param datatype
	 * @param pbn
	 * @param begin
	 * @param end
	 * @param pageParam
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/listdata.json" , method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object listdata(String leftdata, String datatype,String pdttype, String pbn, @DateTimeFormat(pattern="yyyy-MM-dd")Date begin,
			@DateTimeFormat(pattern="yyyy-MM-dd")Date end, PageParam pageParam, HttpServletRequest request){
		String companyid = null;
		String parkid = null;
		String blockid = null;
		if("COMP".equals(datatype)){
			companyid = leftdata;
		}else if(SystemCfg.UI_DATATYPE_PARK.equals(datatype)){
			parkid = leftdata;
		}else if(SystemCfg.UI_DATATYPE_BLOCK.equals(datatype)){
			blockid = leftdata;
		}else{
			return new Pager();
		}
		Pager pager = batchProductsService.list(companyid,parkid, blockid,pdttype, pbn, begin, end, pageParam, getLoginUser(request));
		return pager;
	}
	
	
	
	/**
	 * 添加批次产品信息
	 * @param model
	 * @param leftdata
	 * @param datatype
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/add.do" , method=RequestMethod.GET)
	public String add(ModelMap model, String leftdata,String pdttype, String datatype, HttpServletRequest request){
		if(!SystemCfg.UI_DATATYPE_BLOCK.equals(datatype) || StringUtils.isEmpty(leftdata)){
			model.put("errormessage", "参数错误");
			return "sys/error/error";
		}
		model.put("blockid", leftdata);
		model.put("pdttype", pdttype);
		
		ParkBlockPlantView plant = parkBlockPlantService.getCurrentPlantView(leftdata);
		model.put("plant", plant);
		if(plant == null){
			model.put("errormessage", "该地块没有可用种植信息，请先到“种植管理”模块添加种植信息");
			return "sys/error/error";
		}
		
		Crops crops = cropsService.get(plant.getCropid());
		model.put("crops", crops);
		
		String cropName = cropsService.getCropFullname(plant.getCropid());
		if(cropName == null){
			cropName = plant.getCropName();
		}
		model.put("cropName", cropName);
		
		return "trace/products/products_add";
	}
	
	
	/**
	 * 保存批次产品信息
	 * @param products
	 * @param result
	 * @param plantid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/save.json", method={RequestMethod.POST})
	@ResponseBody
	public Object save(@Valid BatchProducts products, BindingResult result, String plantid, HttpServletRequest request){
		if(result.hasErrors()){
			return getSysErrors(result);
		}
		
		MyUploadFileParam uploadFileParam = new MyUploadFileParam("report", request);
		
		SysError info = batchProductsService.add(products, plantid, uploadFileParam, getLoginUser(request), request);
		return info;
	}
	
	
	/**
	 * 修改批次产品信息
	 * @param model
	 * @param pdtid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/edit.do" , method=RequestMethod.GET)
	public String edit(ModelMap model, String pdtid, HttpServletRequest request){
		BatchProducts products = batchProductsService.get(pdtid);
		model.put("products", products);
		
		ParkBlockPlantView plant = parkBlockPlantService.getPlantView(products.getParkBlockPlant().getPlantid());
		model.put("plant", plant);
		
		Crops crops = cropsService.get(plant.getCropid());
		model.put("crops", crops);
		
		String cropName = cropsService.getCropFullname(plant.getCropid());
		if(cropName == null){
			cropName = plant.getCropName();
		}
		model.put("cropName", cropName);
		
		List<BatchProductsReport> list = batchProductsReportService.listProductsReport(pdtid);
		MyUploadFiles productsReports = new MyUploadFiles();
		for(BatchProductsReport report : list){
			productsReports.addFile(new MyUploadFile(report.getId(), report.getReportUrl(),
					report.getReportName(), report.getReportName(), report.getReportUrl()));
		}
		model.put("productsReports", productsReports);
		
		return "trace/products/products_edit";
	}
	
	
	/**
	 * 保存修改的信息
	 * @param products
	 * @param result
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/update.json", method={RequestMethod.POST})
	@ResponseBody
	public Object update(@Valid BatchProducts products, BindingResult result, HttpServletRequest request){
		if(result.hasErrors()){
			return getSysErrors(result);
		}
		
		MyUploadFileParam uploadFileParam = new MyUploadFileParam("report", request);
		
		SysError info = batchProductsService.update(products, uploadFileParam, getLoginUser(request), request);
		return info;
	}
	
	
	/**
	 * 查看批次产品详情
	 * @param model
	 * @param pdtid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/view.do" , method=RequestMethod.GET)
	public String view(ModelMap model, String pdtid, HttpServletRequest request){
		BatchProducts products = batchProductsService.get(pdtid);
		model.put("products", products);
		
		ParkBlockPlantView plant = parkBlockPlantService.getPlantView(products.getParkBlockPlant().getPlantid());
		model.put("plant", plant);
		
		Crops crops = cropsService.get(plant.getCropid());
		model.put("crops", crops);
		
		String cropName = cropsService.getCropFullname(plant.getCropid());
		if(cropName == null){
			cropName = plant.getCropName();
		}
		model.put("cropName", cropName);
		
		return "trace/products/products_view";
	}
	
	
	/**
	 * 删除批次产品信息
	 * @param pdtid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/delete.json", method={RequestMethod.POST})
	@ResponseBody
	public Object delete(String[] pdtid, HttpServletRequest request){
		if(pdtid==null || pdtid.length==0){
			return new SysError("没有选择任何信息.");
		}
		return batchProductsService.delete(pdtid, getLoginUser(request), request);
	}
	
	
	
	/**
	 * 产品追溯信息
	 * @param model
	 * @param pdtid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/trace.do" , method=RequestMethod.GET)
	public String trace(ModelMap model, String pdtid, HttpServletRequest request){
		BatchProducts products = batchProductsService.get(pdtid);
		model.put("products", products);
		
//		TraceData traceData = batchProductsService.getTraceData(products.getPbn(), false);
//		model.put("traceData", traceData);
		
		return "trace/products/products_trace";
	}
	
	
	/**
	 * 产品追溯二维码
	 * @param model
	 * @param pdtid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/qrcode.do" , method=RequestMethod.GET)
	public String qrcode(ModelMap model, String pdtid, HttpServletRequest request){
		BatchProductsView products = batchProductsService.getProductsView(pdtid);
		model.put("products", products);
		
		if(products==null || StringUtils.isEmpty(products.getPbn())){
			model.put("errormessage", "请先绑定二维码");
			return "sys/error/error";
		}
		
		model.put("qrcode_url", UploadFile.getDomain()+"/mq/"+products.getPbn());
		
		return "trace/products/products_qrcode";
	}
	
	/**
	 * 绑定二维码
	 * @param model
	 * @param pdtid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/bindQrcode.do" , method=RequestMethod.GET)
	public String bindQrcode(ModelMap model, String pdtid, HttpServletRequest request){
		BatchProductsView products = batchProductsService.getProductsView(pdtid);
		model.put("products", products);
		
		return "trace/products/products_bindQrcode";
	}
	
	
	@RequestMapping(value="/listBindQrcode.json" , method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object listBindQrcode(String companyid, String parkid, String cropid, PageParam pageParam, HttpServletRequest request){
		return qrNumService.listBind(companyid, parkid, cropid, pageParam);
	}
	
	@RequestMapping(value="/addBindQrcode.json" , method={RequestMethod.POST})
	@ResponseBody
	public Object addBindQrcode(String pdtid, String qrnumid){
		return batchProductsService.addBindQrcode(pdtid, qrnumid);
	}
	
	
	@RequestMapping(value="/doexport.do", method=RequestMethod.GET)
	public String doexport(String pdttype, String leftdata, String datatype, @DateTimeFormat(pattern="yyyy-MM-dd")Date begin,
			@DateTimeFormat(pattern="yyyy-MM-dd")Date end, PageParam pageParam, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String companyid = null;
		String parkid = null;
		String blockid = null;
		String filename = null;
		if("COMP".equals(datatype)){
			companyid = leftdata;
			Company company = companyService.get(companyid);
			if(company != null){
				filename = company.getCompanyName();
			}
		}else if(SystemCfg.UI_DATATYPE_PARK.equals(datatype)){
			parkid = leftdata;
			FarmPark farmPark = farmParkService.get(parkid);
			if(farmPark != null){
				filename = farmPark.getParkName();
			}
		}else if(SystemCfg.UI_DATATYPE_BLOCK.equals(datatype)){
			blockid = leftdata;
			ParkBlock parkBlock = parkBlockService.get(blockid);
			if(parkBlock != null){
				FarmPark farmPark = farmParkService.get(parkBlock.getFarmPark().getParkid());
				filename = farmPark.getParkName()+"-"+parkBlock.getBlockName();
			}
		}
		
		if(StringUtils.isEmpty(filename)){
			responseText("参数缺失，缺少园区或地块参数，导出失败。", response);
			return null;
		}
		
		String temps = null;
		if("1".equals(pdttype)){
			temps = servletContext.getRealPath("/WEB-INF/excelTemps/products_zz_export.xlsx");
		}
		
		if(StringUtils.isEmpty(temps)){
			responseText("参数错误，数据类型无效，导出失败。", response);
			return null;
		}
		
		File tempsFile = new File(temps);
		if(!tempsFile.isFile()){
			responseText("数据模板文件丢失，导出失败。", response);
			return null;
		}
		
		filename = filename + "-产品批次信息.xlsx";
		
		List<BatchProductsView> list = batchProductsService.listForExport(companyid, parkid, blockid, pdttype, begin, end, getLoginUser(request));
		if(list == null){
			list = new ArrayList<>();
		}
		
		filename = java.net.URLEncoder.encode(filename, "UTF-8");
		response.resetBuffer();
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'" + filename);
		
		OutputStream outputStream = response.getOutputStream();
		ExcelUtil.exportExcel(tempsFile, outputStream, list);
		outputStream.close();
		return null;
	}
	
	
	//向响应写入文本
	protected void responseText(String text, HttpServletResponse response) throws Exception {
		response.resetBuffer();
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write("<html><body>");
		out.write("<h2>"+text+"</h2>");
		out.write("</body></html>");
		out.close();
	}
	
}
